package com.ai.web.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Getter;
import lombok.Setter;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.ai.web.cache.Constants;
import com.ai.web.cache.UserContext;
import com.ai.web.util.ExportUtils;
import com.ai.web.util.Utils;
import com.tiny.persistence.repository.impl.TinyApplicationContext;

@Controller
@SessionAttributes(Constants.USER_CONTEXT)
public class BaseController {
	
    private static Logger logger = Logger.getLogger(BaseController.class);

	@Setter @Getter private HttpServletRequest request;
	@Setter @Getter private HttpServletResponse response;
	
	protected Map<String, Object> buildCondition(Map<String, Object> paramMap) {
		Map<String, Object> conditionMap = new HashMap<String, Object>();
		UserContext uc = (UserContext) request.getSession().getAttribute(Constants.USER_CONTEXT);
		for (Entry<String, Object> entry : paramMap.entrySet()) {
			Object obj = entry.getValue();
			if (obj != null && !obj.toString().trim().equals("")) {
				if (entry.getKey().equals(Constants.KEY_PAGE_FROM)) {
					conditionMap.put(entry.getKey(), Integer.parseInt(obj.toString()));
				}else if(entry.getKey().equals(Constants.KEY_PAGE_SIZE)){
					uc.setPageSize(Integer.parseInt(obj.toString()));
				}else {
					conditionMap.put(entry.getKey(), obj.toString());
				}
			}
		}
		conditionMap.put(Constants.USER_CONTEXT, uc);
		int pageFrom =1;
		if(conditionMap.get(Constants.KEY_PAGE_FROM)!=null){
			pageFrom = (Integer) conditionMap.get(Constants.KEY_PAGE_FROM);
		}
		
		int recordFrom = pageFrom * uc.getPageSize() - uc.getPageSize();
		conditionMap.put(Constants.KEY_RECORD_FROM, recordFrom);
		
		return conditionMap;
	}
	
	protected void setCookie(String name, Object value) {
		
		Cookie cookie = new Cookie(name, value.toString());
        cookie.setPath("/");
        cookie.setMaxAge(360 * 24 * 60 * 60);
        
        response.addCookie(cookie);
	}
	
	protected List<Integer> getDeleteIds(String delIds) {
		List<Integer> delIdList = new ArrayList<Integer>();
		String[] strs = delIds.split("@");
		for (String str : strs) {
			if (!Utils.isEmpty(str)) {
				delIdList.add(Integer.parseInt(str));
			}
		}
		return delIdList;
	}
	
	@RequestMapping(value="/main")
	public String main(Model model) {
		UserContext uc = (UserContext) request.getSession().getAttribute(Constants.USER_CONTEXT);
		model.addAttribute("user", uc.getBgUser());
		return "main";
	}
	
//	@Transactional(propagation=Propagation.NOT_SUPPORTED)
    @ResponseBody
	@RequestMapping(value = "/init")
	public String initMenu() {
    	UserContext uc = (UserContext) request.getSession().getAttribute(Constants.USER_CONTEXT);
    	if(uc.getBgUser().getBgRole().getId() == Constants.SYSTEM_MANAGE_ROLE)
    	TinyApplicationContext.getJdbcTemplateBean().execute("delete from bg_role_menu");
		TinyApplicationContext.getJdbcTemplateBean().execute("delete from bg_menu");
		TinyApplicationContext.getJdbcTemplateBean().execute("delete from bg_user");
		TinyApplicationContext.getJdbcTemplateBean().execute("delete from bg_role");
		TinyApplicationContext.getJdbcTemplateBean().execute("delete from wx_role_menu");
		TinyApplicationContext.getJdbcTemplateBean().execute("delete from wx_menu");
		TinyApplicationContext.getJdbcTemplateBean().execute("delete from wx_user");
		TinyApplicationContext.getJdbcTemplateBean().execute("delete from wx_role");
		TinyApplicationContext.getJdbcTemplateBean().execute("delete from wx_keyword_config");
		initMethod("bg_menu", "bgMenu.sql");
		initMethod("bg_role", "bgRole.sql");
		initMethod("bg_role_menu", "bgRoleMenu.sql");
		initMethod("bg_user", "bgUser.sql");
		initMethod("wx_menu", "wxMenu.sql");
		initMethod("wx_role", "wxRole.sql");
		initMethod("wx_role_menu", "wxRoleMenu.sql");
		initMethod("wx_keyword_config", "wxKeywordConfig.sql");
		return "success";
	}
	
	private void initMethod(String tableName, String fileName) {

		// 初始化菜单
		List<String> sqlList = new ArrayList<String>();

		try {
			// 读文件内容
			File data = new File(this.getClass().getResource("/").getPath()
					+ "initDbSql/" + fileName);

			List<File> fileList = new ArrayList<File>();
			fileList.add(data);
			// fileList.add(wxMenu);

			for (File file : fileList) {
				InputStreamReader isr = new InputStreamReader(
						new FileInputStream(file), "utf-8");
				BufferedReader br = new BufferedReader(isr);

				String str = null;
				while ((str = br.readLine()) != null) {
					sqlList.add(str);
				}
				br.close();
				isr.close();
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}

		String[] menusql = new String[sqlList.size()];
		sqlList.toArray(menusql);
		TinyApplicationContext.getJdbcTemplateBean().batchUpdate(menusql);
		List<Map<String, Object>> list = TinyApplicationContext
				.getJdbcTemplateBean().queryForList(
						"select * from " + tableName);
		for (Map<String, Object> map : list) {
			System.out.println(map.toString());
		}
		logger.info("初始化菜单完毕");
	}
	
	protected void exportXls(List<Map<String, String>> dataSet, String[] keys,
			String fileName) {
		
		try {
			if (fileName == null) {
				fileName = "export.xls";
			} else {
				try {
					fileName = URLEncoder.encode(fileName, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					fileName = "export.xls";
				}
			}
			HttpServletResponse response = getResponse();
			response.setHeader("Content-disposition", "attachment; filename="
					+ fileName);// filename是下载的xls的名，建议最好用英文
			response.setContentType("application/msexcel;charset=UTF-8");// 设置类型
			response.setHeader("Pragma", "No-cache");// 设置头
			response.setHeader("Cache-Control", "no-cache");// 设置头
			response.setDateHeader("Expires", 0);// 设置日期头

			ExportUtils.export(dataSet, keys, response.getOutputStream());
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}

	}
}
